import os
import sys
import django
import random
from datetime import datetime, timedelta
from decimal import Decimal
import uuid
import asyncio
from asgiref.sync import sync_to_async
from django.utils import timezone
from django.db import transaction

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fresh_chain_backend.settings')
django.setup()

# 导入模型
from django.contrib.auth import get_user_model
from users.models import Supplier, DeliveryStaff
from products.models import Category, Product
from warehouse.models import Warehouse, Inventory, InventoryRecord, PurchaseOrder, PurchaseOrderItem
from orders.models import Order, OrderItem
from delivery.models import DeliveryArea, DeliverymanArea, DeliveryTask, DeliveryStatusRecord

User = get_user_model()

# 清除现有数据  
def clear_existing_data():
    print('清除现有数据...')
    DeliveryStatusRecord.objects.all().delete()
    DeliveryTask.objects.all().delete()
    DeliverymanArea.objects.all().delete()
    DeliveryArea.objects.all().delete()
    OrderItem.objects.all().delete()
    Order.objects.all().delete()
    PurchaseOrderItem.objects.all().delete()
    PurchaseOrder.objects.all().delete()
    InventoryRecord.objects.all().delete()
    Inventory.objects.all().delete()
    Product.objects.all().delete()
    Category.objects.all().delete()
    Warehouse.objects.all().delete()
    DeliveryStaff.objects.all().delete()
    Supplier.objects.all().delete()
    User.objects.filter(username__in=['admin', 'purchaser', 'salesman', 'delivery_admin']).delete()
    # 删除所有配送员和客户
    User.objects.filter(role__in=['deliveryman', 'customer']).delete()

# 创建用户
def create_users():
    print('创建用户...')
    # 创建管理员
    admin = User.objects.create_user(
        username='admin',
        password='admin123',
        email='admin@example.com',
        phone='13800000000',
        role='admin',
        is_staff=True,
        is_superuser=True
    )
    
    # 创建采购员
    purchaser = User.objects.create_user(
        username='purchaser',
        password='purchaser123',
        email='purchaser@example.com',
        phone='13800000001',
        role='purchaser'
    )
    
    # 创建销售员
    salesman = User.objects.create_user(
        username='salesman',
        password='salesman123',
        email='salesman@example.com',
        phone='13800000002',
        role='salesman'
    )
    
    # 创建配送管理员
    delivery_admin = User.objects.create_user(
        username='delivery_admin',
        password='delivery_admin123',
        email='delivery_admin@example.com',
        phone='13800000006',
        role='delivery_admin',
        is_staff=True
    )
    
    # 创建配送员 - 北京市
    delivery_staff_list = []
    for i in range(1, 8):  # 创建7个配送员
        deliveryman = User.objects.create_user(
            username=f'deliveryman{i}',
            password=f'deliveryman{i}123',
            email=f'deliveryman{i}@example.com',
            phone=f'1380000{1000+i}',
            role='deliveryman'  # 这里使用的是正确的角色名称
        )
        
        # 创建配送员资料
        DeliveryStaff.objects.create(
            user=deliveryman,
            vehicle_number=f'京A{10000+i}',
            service_area='北京市'
        )
        delivery_staff_list.append(deliveryman)
    
    # 创建客户 - 北京市
    customers = []
    for i in range(1, 11):  # 创建10个客户
        customer = User.objects.create_user(
            username=f'customer{i}',
            password=f'customer{i}123',
            email=f'customer{i}@example.com',
            phone=f'1390000{1000+i}',
            role='customer',
            address=f'北京市朝阳区东三环{i}号'
        )
        customers.append(customer)
    
    # 创建供应商用户
    supplier_user = User.objects.create_user(
        username='supplier1',
        password='supplier1123',
        email='supplier@example.com',
        phone='13800000005',
        role='supplier',
        company_name='优质生鲜供应有限公司',
        business_license='123456789012345'
    )
    
    # 创建供应商资料
    supplier = Supplier.objects.create(
        user=supplier_user,
        company_name='优质生鲜供应有限公司',
        business_license='123456789012345'
    )
    
    return {
        'admin': admin,
        'purchaser': purchaser,
        'salesman': salesman,
        'delivery_admin': delivery_admin,
        'deliverymen': delivery_staff_list,  # 这里只是一个字典键名，表示配送员列表
        'customers': customers,
        'supplier': supplier
    }

# 创建产品类别
def create_categories():
    print('创建产品类别...')
    categories = []
    for name, desc in [
        ('水果', '新鲜水果类别'),
        ('蔬菜', '绿色蔬菜类别'),
        ('肉类', '优质肉类类别'),
        ('海鲜', '新鲜海鲜类别')
    ]:
        category = Category.objects.create(name=name, description=desc)
        categories.append(category)
    return categories

# 创建仓库
def create_warehouses(admin):
    print('创建仓库...')
    warehouses = []
    
    # 北京仓库
    for name, location, type_name, capacity in [
        ('常温仓库', '北京市朝阳区', 'normal', 1000),
        ('冷藏仓库', '北京市海淀区', 'cold', 500),
        ('冷冻仓库', '北京市丰台区', 'frozen', 300)
    ]:
        warehouse = Warehouse.objects.create(
            name=name,
            location=location,
            type=type_name,
            capacity=capacity,
            manager=admin,
            status='active'
        )
        warehouses.append(warehouse)
    
    return warehouses

# 创建产品
def create_products(categories, supplier):
    print('创建产品...')
    products = []
    
    # 水果类产品
    fruit_products = [
        ('F001', '苹果', '斤', Decimal('5.99'), Decimal('3.50')),
        ('F002', '香蕉', '斤', Decimal('4.50'), Decimal('2.80')),
        ('F003', '橙子', '斤', Decimal('6.50'), Decimal('4.00')),
        ('F004', '葡萄', '斤', Decimal('8.99'), Decimal('5.50')),
        ('F005', '西瓜', '个', Decimal('15.00'), Decimal('10.00'))
    ]
    
    # 蔬菜类产品
    vegetable_products = [
        ('V001', '白菜', '斤', Decimal('2.50'), Decimal('1.20')),
        ('V002', '土豆', '斤', Decimal('3.00'), Decimal('1.50')),
        ('V003', '西红柿', '斤', Decimal('4.50'), Decimal('2.50')),
        ('V004', '黄瓜', '斤', Decimal('3.50'), Decimal('1.80')),
        ('V005', '茄子', '斤', Decimal('4.00'), Decimal('2.00'))
    ]
    
    # 肉类产品
    meat_products = [
        ('M001', '猪肉', '斤', Decimal('18.00'), Decimal('12.00')),
        ('M002', '牛肉', '斤', Decimal('35.00'), Decimal('25.00')),
        ('M003', '羊肉', '斤', Decimal('32.00'), Decimal('22.00')),
        ('M004', '鸡肉', '斤', Decimal('15.00'), Decimal('9.00')),
        ('M005', '鸭肉', '斤', Decimal('16.00'), Decimal('10.00'))
    ]
    
    # 海鲜类产品
    seafood_products = [
        ('S001', '鲈鱼', '斤', Decimal('25.00'), Decimal('18.00')),
        ('S002', '虾', '斤', Decimal('45.00'), Decimal('32.00')),
        ('S003', '螃蟹', '斤', Decimal('60.00'), Decimal('42.00')),
        ('S004', '贝类', '斤', Decimal('30.00'), Decimal('20.00')),
        ('S005', '鱿鱼', '斤', Decimal('28.00'), Decimal('19.00'))
    ]
    
    # 按类别创建产品
    all_products = [
        (categories[0], fruit_products),
        (categories[1], vegetable_products),
        (categories[2], meat_products),
        (categories[3], seafood_products)
    ]
    
    # 描述模板
    description_templates = {
        '水果': [
            '新鲜采摘，汁多味甜的{name}，每日优选，健康生活的首选！',
            '品尝来自大自然的馈赠，每一口{name}都是阳光的味道。',
            '维C满满，美味可口的{name}，助您活力一整天！'
        ],
        '蔬菜': [
            '农场直供，绿色无公害{name}，为您和家人的健康保驾护航。',
            '清脆爽口，营养丰富的{name}，简单烹饪即享美味。',
            '田园风光，尽在口中，新鲜{name}让您的餐桌更添色彩。'
        ],
        '肉类': [
            '精选上等{name}，肉质鲜嫩，口感醇厚，满足您的味蕾。',
            '源头好肉，安全放心，我们的{name}是您健康饮食的理想选择。',
            '无论是煎炒烹炸，{name}都能展现其独特风味，让家常菜更美味。'
        ],
        '海鲜': [
            '深海捕捞，鲜活直达的{name}，带给您海洋的纯正滋味。',
            '肉质饱满，鲜美无比的{name}，是海鲜爱好者的不二之选。',
            '来自纯净海域的{name}，营养价值高，味道鲜美，让您尽享海的味道。'
        ]
    }

    for category, product_list in all_products:
        for code, name, unit, price, cost_price in product_list:
            # 随机生成进货日期和到期日期
            purchase_date = datetime.now().date() - timedelta(days=random.randint(1, 10))
            expiry_date = purchase_date + timedelta(days=random.randint(10, 30))
            
            # 根据类别选择描述模板
            category_name = category.name
            if category_name in description_templates:
                description = random.choice(description_templates[category_name]).format(name=name)
            else:
                description = f'优质{name}，新鲜美味，品质保证。' # 默认描述

            # 创建产品名称到图片文件名的映射
            name_to_image = {
                '苹果': 'apple.png',
                '香蕉': 'banana.jpg',
                '橙子': 'orange.jpg',
                '葡萄': 'grape.jpg',
                '西瓜': 'watermelon.jpg',
                '白菜': 'cabbage.jpg',
                '土豆': 'potato.jpg',
                '西红柿': 'tomato.jpg',
                '黄瓜': 'Cucumber.jpg',  # 注意首字母大写
                '茄子': 'eggplant.jpg',
                '猪肉': 'pork.jpg',
                '牛肉': 'beef.jpg',
                '羊肉': 'mutton.jpg',
                '鸡肉': 'chicken.jpg',
                '鸭肉': 'duck meat.jpg',  # 注意空格
                '鲈鱼': 'sea bass.jpg',  # 注意空格
                '虾': 'shrimp.jpg',
                '螃蟹': 'crab.jpg',
                '贝类': 'shellfish.jpg',
                '鱿鱼': 'squid.jpg'
            }
            
            product = Product.objects.create(
                product_code=code,
                name=name,
                category=category,
                supplier=supplier,
                unit=unit,
                price=price,
                cost_price=cost_price,
                min_stock=10,
                purchase_date=purchase_date,
                expiry_date=expiry_date,
                expiry_warning=3,
                description=description, # 使用新的描述
                image_url=f'products/{name_to_image.get(name, name + ".jpg")}',
                status='active'
            )
            products.append(product)
    
    return products

# 创建库存
def create_inventory(products, warehouses):
    print('创建库存...')
    inventories = []
    
    for product in products:
        # 为每个产品在随机仓库中创建库存
        warehouse = random.choice(warehouses)
        
        # 随机生成库存数量
        current_stock = random.randint(5, 50)
        min_stock = 10
        max_stock = 100
        
        # 使用产品的进货日期和到期日期
        purchase_date = product.purchase_date
        expiry_date = product.expiry_date
        
        # 根据库存量确定状态
        if current_stock < min_stock:
            status = 'warning'
        elif current_stock > max_stock:
            status = 'overflow'
        else:
            status = 'normal'
        
        inventory = Inventory.objects.create(
            product=product,
            warehouse=warehouse,
            current_stock=current_stock,
            min_stock=min_stock,
            max_stock=max_stock,
            purchase_date=purchase_date,
            expiry_date=expiry_date,
            status=status
        )
        inventories.append(inventory)
    
    return inventories

# 创建库存记录
def create_inventory_records(inventories, users):
    print('创建库存记录...')
    records = []
    
    for inventory in inventories:
        # 创建入库记录
        in_record = InventoryRecord.objects.create(
            inventory=inventory,
            operation_type='in',
            quantity=inventory.current_stock,
            operator=users['purchaser'],
            note='初始入库'
        )
        records.append(in_record)
        
        # 为部分库存创建出库记录
        if random.random() < 0.5:  # 50%的概率创建出库记录
            out_quantity = random.randint(1, 5)
            if out_quantity <= inventory.current_stock:
                out_record = InventoryRecord.objects.create(
                    inventory=inventory,
                    operation_type='out',
                    quantity=out_quantity,
                    operator=users['salesman'],
                    note='销售出库'
                )
                records.append(out_record)
                
                # 更新库存
                inventory.current_stock -= out_quantity
                inventory.save()
    
    return records

# 创建采购订单
def create_purchase_orders(products, warehouses, users):
    print('创建采购订单...')
    orders = []
    
    # 创建50个采购订单（增加数量）
    for i in range(50):
        # 模拟更真实的业务时间分布
        # 1. 生成基准日期（例如，从当前日期往前推90天作为起始点）
        base_date = timezone.now() - timedelta(days=90)
        
        # 2. 模拟工作日和工作时间的分布
        # 随机选择一个工作日（周一到周五）的偏移量
        workday_offset = random.randint(0, 90)  # 90天内的某一天
        order_date = base_date + timedelta(days=workday_offset)
        
        # 3. 模拟工作时间（早上9点到下午6点）
        business_hour = random.randint(9, 18)  # 工作时间9:00-18:00
        business_minute = random.randint(0, 59)
        
        # 4. 组合成最终的订单创建时间
        order_creation_time = order_date.replace(
            hour=business_hour,
            minute=business_minute,
            second=random.randint(0, 59)
        )
        
        # 生成订单编号
        date_str = order_creation_time.strftime('%Y%m%d')
        random_num = random.randint(1000, 9999)
        order_number = f'PO{date_str}{random_num}'
        
        # 随机选择供应商名称
        supplier_name = '优质生鲜供应有限公司'
        
        # 创建采购订单
        order = PurchaseOrder.objects.create(
            order_number=order_number,
            supplier=supplier_name,
            purchaser=users['purchaser'],
            total_amount=Decimal('0'),  # 初始总金额为0
            status=random.choice(['pending', 'confirmed', 'received', 'cancelled']),
            remark=f'采购订单备注 {i+1}'
        )
        
        # 更新创建时间为模拟时间
        PurchaseOrder.objects.filter(id=order.id).update(created_at=order_creation_time)
        
        # 为订单添加3-7个商品项（增加数量范围）
        total_amount = Decimal('0')
        for _ in range(random.randint(3, 5)):
            product = random.choice(products)
            quantity = random.randint(10, 30)
            unit_price = product.cost_price
            total_price = unit_price * quantity
            
            # 创建采购订单项
            order_item = PurchaseOrderItem.objects.create(
                purchase_order=order,
                product=product,
                quantity=quantity,
                unit_price=unit_price,
                total_price=total_price,
                warehouse=random.choice(warehouses)
            )
            
            # 更新创建时间为模拟时间
            PurchaseOrderItem.objects.filter(id=order_item.id).update(created_at=order_creation_time)
            
            total_amount += total_price
        
        # 更新订单总金额，但不使用save()方法，而是使用update()方法
        # 这样可以避免触发save()方法可能导致的created_at字段被重置
        PurchaseOrder.objects.filter(id=order.id).update(total_amount=total_amount)
        
        # 重新获取更新后的订单对象
        order = PurchaseOrder.objects.get(id=order.id)
        orders.append(order)
    
    return orders

# 定义北京市区域信息
def get_city_districts():
    return ['朝阳区', '海淀区', '丰台区', '西城区', '东城区']

# 创建配送区域
def create_delivery_areas():
    print('创建配送区域...')
    areas = []
    
    districts = get_city_districts()
    
    for district in districts:
        area = DeliveryArea.objects.create(
            name=f'北京市{district}',
            description=f'北京市{district}配送范围',
            status='active'
        )
        areas.append(area)
    
    return areas

# 创建配送员区域关联
def create_deliveryman_areas(delivery_staff_list, areas):
    print('创建配送员区域关联...')
    deliveryman_areas = []
    
    # 为每个配送员分配所有区域
    for deliveryman in delivery_staff_list:
        for area in areas:
            deliveryman_area = DeliverymanArea.objects.create(
                deliveryman=deliveryman,
                area=area
            )
            deliveryman_areas.append(deliveryman_area)
    
    return deliveryman_areas

# 创建销售订单
def create_sales_orders(products, warehouses, users):
    print('创建销售订单...')
    orders = []
    
    # 定义不同状态的订单数量 (增加数量)
    status_counts = {
        'paid': 10,      # 已付款 (增加到50)
        'shipped': 40,   # 已发货 (增加到40)
        'completed': 100, # 已完成 (增加到80)
        'cancelled': 10  # 已取消 (增加到30)
    }
    
    # 获取区域信息
    districts = get_city_districts()
    
    # 创建不同状态的订单
    for status_key, count in status_counts.items():
        for i in range(count):
            # 随机选择客户
            customer = random.choice(users['customers'])
            
            # 随机选择区域
            district = random.choice(districts)
            address = f'北京市{district}某某路{random.randint(1, 100)}号'
            
            # 随机生成过去90天内的时间（从30天改为90天）
            days_ago = random.randint(0, 90)
            random_hours = random.randint(0, 23)
            random_minutes = random.randint(0, 59)
            random_seconds = random.randint(0, 59)
            order_creation_time = timezone.now() - timedelta(days=days_ago, hours=random_hours, minutes=random_minutes, seconds=random_seconds)
            
            # 检查日期是否为6.10或6.11
            is_recent_date = (order_creation_time.month == 6 and 
                             (order_creation_time.day == 10 or order_creation_time.day == 11))
            
            # 根据日期调整状态
            actual_status = status_key
            if (status_key in ['paid', 'shipped']) and not is_recent_date:
                # 如果不是6.10或6.11，且状态是已付款或已发货，则改为已完成或已取消
                actual_status = random.choice(['completed', 'cancelled'])
            
            # 生成订单编号
            order_date_str = order_creation_time.strftime('%Y%m%d')
            order_number = f'SO{order_date_str}{str(uuid.uuid4().int)[:6]}'
            
            # 创建销售订单
            order = Order.objects.create(
                order_number=order_number,
                customer=customer,
                salesman=users['salesman'],
                total_amount=Decimal('0'),  # 初始总金额为0
                status=actual_status,  # 使用调整后的状态
                payment_method='微信支付' if actual_status != 'cancelled' else None,
                payment_time=order_creation_time if actual_status != 'cancelled' else None,
                address=address,
                phone=customer.phone,
                remark=f'北京市销售订单 {i+1}'
                # 如果 Order 模型中的 created_at 不是 auto_now_add=True, 你可能也需要设置它:
                # created_at=order_creation_time 
            )
            
            # 为订单添加2-5个商品项（增加商品数量范围）
            total_amount = Decimal('0')
            for _ in range(random.randint(2, 5)):
                product = random.choice(products)
                quantity = random.randint(1, 8)  # 增加数量范围
                unit_price = product.price
                total_price = unit_price * quantity
                
                # 随机选择仓库
                warehouse = random.choice(warehouses)
                
                # 创建销售订单项
                OrderItem.objects.create(
                    order=order,
                    product=product,
                    quantity=quantity,
                    unit_price=unit_price,
                    total_price=total_price,
                    warehouse=warehouse
                )
                
                total_amount += total_price
            
            # 更新订单总金额
            order.total_amount = total_amount
            order.save()
            
            orders.append(order)
    
    return orders

# 创建配送任务
def create_delivery_tasks(orders, users):
    print('创建配送任务...')
    tasks = []
    
    for order in orders:
        # 修改：对所有订单（包括已取消的）都创建配送任务
        # 随机选择配送员（对于已取消订单，可以不分配配送员）
        deliveryman = random.choice(users['deliverymen']) if order.status != 'cancelled' else None
        
        # 生成配送编号
        delivery_number = f'DT{timezone.now().strftime("%Y%m%d")}{str(uuid.uuid4().int)[:6]}'
        
        # 根据订单状态设置配送任务状态
        if order.status == 'paid':
            task_status = 'assigned'  # 已分配
        elif order.status == 'shipped':
            task_status = 'delivering'  # 配送中
        elif order.status == 'completed':
            task_status = 'completed'  # 已完成
        else:  # cancelled
            task_status = 'cancelled'  # 已取消
        
        # 确保 order.payment_time 存在（对于非取消订单）
        order_time = order.payment_time if order.payment_time else timezone.now()

        # 创建配送任务
        task = DeliveryTask.objects.create(
            delivery_number=delivery_number,
            sales_order=order,
            deliveryman=deliveryman,
            status=task_status,
            priority=random.choice(['high', 'medium', 'low']),
            rejection_count=0,  # 初始拒绝次数为0
            # 预计送达时间在订单支付后的1-3天内（对于已取消订单可以为空）
            estimated_delivery_time=order_time + timedelta(days=random.randint(1, 3)) if order.status != 'cancelled' else None,
            # 实际送达时间，如果已完成，则在预计时间附近或稍早
            actual_delivery_time=order_time + timedelta(days=random.randint(0,2), hours=random.randint(0,23)) if task_status == 'completed' else None,
            note=f'配送任务备注 {order.order_number}'
        )
        tasks.append(task)
    
    return tasks

# 创建配送状态记录
def create_delivery_status_records(tasks, users):
    print('创建配送状态记录...')
    records = []
    delivery_admin_user = users['delivery_admin']
    all_deliverymen = users['deliverymen']

    # 拒绝原因列表
    rejection_reasons = ['distance_too_far', 'workload_too_high', 'vehicle_issue', 'weather_condition', 'personal_reason']
    
    # 区域信息
    districts = get_city_districts()
    
    # 计数器，用于跟踪创建了多少个awaiting_manual_assignment状态的任务
    awaiting_manual_count = 0
    awaiting_manual_target = 2  # 目标数量

    for task in tasks:
        # 跳过已取消的任务，不为其创建状态记录
        if task.status == 'cancelled':
            continue
            
        order_time = task.sales_order.payment_time if task.sales_order.payment_time else timezone.now()

        # 随机决定任务的处理方式
        # 0: 直接接受并完成
        # 1: 一次拒绝后接受
        # 2: 两次拒绝后管理员强制分配
        process_type = random.randint(0, 2)
        
        # 如果还没有达到目标数量，强制设置为类型2
        if awaiting_manual_count < awaiting_manual_target and task.status == 'paid':
            process_type = 2
        
        # 随机选择区域
        district = random.choice(districts)
        
        if process_type == 0:  # 直接接受并完成
            if task.status == 'assigned':
                # 创建已分配状态记录 (在订单支付后不久)
                assigned_time = order_time + timedelta(minutes=random.randint(5, 30))
                record = DeliveryStatusRecord.objects.create( 
                    delivery_task=task, 
                    status='assigned', 
                    operator=delivery_admin_user, 
                    note=f'系统自动分配任务给配送员: {task.deliveryman.username}，区域: 北京市{district}' 
                ) 
                DeliveryStatusRecord.objects.filter(id=record.id).update(created_at=assigned_time)
                records.append(record)
            
            elif task.status == 'delivering':
                assigned_time = order_time + timedelta(minutes=random.randint(5, 30))
                # 创建已分配状态记录
                record1 = DeliveryStatusRecord.objects.create(
                    delivery_task=task,
                    status='assigned',
                    operator=delivery_admin_user,
                    note=f'系统自动分配任务给配送员: {task.deliveryman.username}，区域: 北京市{district}'
                )
                DeliveryStatusRecord.objects.filter(id=record1.id).update(created_at=assigned_time)
                records.append(record1)
                
                # 创建配送中状态记录 (在分配后1-2小时)
                delivering_time = assigned_time + timedelta(hours=random.randint(1,2), minutes=random.randint(0,59))
                record2 = DeliveryStatusRecord.objects.create(
                    delivery_task=task,
                    status='delivering',
                    operator=task.deliveryman,
                    note='配送员开始配送'
                )
                DeliveryStatusRecord.objects.filter(id=record2.id).update(created_at=delivering_time)
                records.append(record2)
            
            elif task.status == 'completed':
                assigned_time = order_time + timedelta(minutes=random.randint(5, 30))
                delivering_time = assigned_time + timedelta(hours=random.randint(1,2), minutes=random.randint(0,59))
                completed_time = delivering_time + timedelta(hours=random.randint(1,5), minutes=random.randint(0,59))
                
                if task.actual_delivery_time and completed_time > task.actual_delivery_time:
                    completed_time = task.actual_delivery_time

                # 创建已分配状态记录
                record1 = DeliveryStatusRecord.objects.create(
                    delivery_task=task,
                    status='assigned',
                    operator=delivery_admin_user,
                    note=f'系统自动分配任务给配送员: {task.deliveryman.username}，区域: 北京市{district}'
                )
                DeliveryStatusRecord.objects.filter(id=record1.id).update(created_at=assigned_time)
                records.append(record1)
                
                # 创建配送中状态记录
                record2 = DeliveryStatusRecord.objects.create(
                    delivery_task=task,
                    status='delivering',
                    operator=task.deliveryman,
                    note='配送员开始配送'
                )
                DeliveryStatusRecord.objects.filter(id=record2.id).update(created_at=delivering_time)
                records.append(record2)
                
                # 创建已完成状态记录
                record3 = DeliveryStatusRecord.objects.create(
                    delivery_task=task,
                    status='completed',
                    operator=task.deliveryman,
                    note='配送员已完成配送'
                )
                DeliveryStatusRecord.objects.filter(id=record3.id).update(created_at=completed_time)
                records.append(record3)
                
        elif process_type == 1:  # 一次拒绝后接受
            # 初始分配
            assigned_time = order_time + timedelta(minutes=random.randint(5, 30))
            initial_deliveryman = task.deliveryman
            
            # 创建初始分配记录
            record1 = DeliveryStatusRecord.objects.create(
                delivery_task=task,
                status='assigned',
                operator=delivery_admin_user,
                note=f'系统自动分配任务给配送员: {initial_deliveryman.username}，区域: 北京市{district}'
            )
            DeliveryStatusRecord.objects.filter(id=record1.id).update(created_at=assigned_time)
            records.append(record1)
            
            # 拒绝记录
            rejection_time = assigned_time + timedelta(minutes=random.randint(10, 30))
            rejection_reason = random.choice(rejection_reasons)
            record2 = DeliveryStatusRecord.objects.create(
                delivery_task=task,
                status='rejected',
                operator=initial_deliveryman,
                note=f'配送员 {initial_deliveryman.username} 拒绝任务，原因: {rejection_reason}'
            )
            DeliveryStatusRecord.objects.filter(id=record2.id).update(created_at=rejection_time)
            records.append(record2)
            
            # 更新任务的拒绝计数
            task.rejection_count = 1
            task.save()
            
            # 重新分配给另一个配送员
            new_deliveryman = random.choice([dm for dm in all_deliverymen if dm != initial_deliveryman])
            task.deliveryman = new_deliveryman
            task.save()
            
            reassign_time = rejection_time + timedelta(minutes=random.randint(5, 15))
            record3 = DeliveryStatusRecord.objects.create(
                delivery_task=task,
                status='assigned',
                operator=delivery_admin_user,
                note=f'系统自动分配任务给配送员: {new_deliveryman.username}，区域: 北京市{district}'
            )
            DeliveryStatusRecord.objects.filter(id=record3.id).update(created_at=reassign_time)
            records.append(record3)
            
            # 根据任务状态添加后续记录
            if task.status in ['delivering', 'completed']:
                delivering_time = reassign_time + timedelta(hours=random.randint(1,2), minutes=random.randint(0,59))
                record4 = DeliveryStatusRecord.objects.create(
                    delivery_task=task,
                    status='delivering',
                    operator=new_deliveryman,
                    note='配送员开始配送'
                )
                DeliveryStatusRecord.objects.filter(id=record4.id).update(created_at=delivering_time)
                records.append(record4)
                
                if task.status == 'completed':
                    completed_time = delivering_time + timedelta(hours=random.randint(1,5), minutes=random.randint(0,59))
                    if task.actual_delivery_time and completed_time > task.actual_delivery_time:
                        completed_time = task.actual_delivery_time
                    
                    record5 = DeliveryStatusRecord.objects.create(
                        delivery_task=task,
                        status='completed',
                        operator=new_deliveryman,
                        note='配送员已完成配送'
                    )
                    DeliveryStatusRecord.objects.filter(id=record5.id).update(created_at=completed_time)
                    records.append(record5)
            
        elif process_type == 2:  # 两次拒绝后管理员强制分配
            # 更新任务的拒绝计数
            task.rejection_count = 2
            task.save()
            
            # 初始分配
            assigned_time = order_time + timedelta(minutes=random.randint(5, 30))
            initial_deliveryman = random.choice(all_deliverymen)
            
            # 创建初始分配记录
            record1 = DeliveryStatusRecord.objects.create(
                delivery_task=task,
                status='assigned',
                operator=delivery_admin_user,
                note=f'系统自动分配任务给配送员: {initial_deliveryman.username}，区域: 北京市{district}'
            )
            DeliveryStatusRecord.objects.filter(id=record1.id).update(created_at=assigned_time)
            records.append(record1)
            
            # 第一次拒绝
            rejection_time1 = assigned_time + timedelta(minutes=random.randint(10, 30))
            rejection_reason1 = random.choice(rejection_reasons)
            record2 = DeliveryStatusRecord.objects.create(
                delivery_task=task,
                status='rejected',
                operator=initial_deliveryman,
                note=f'配送员 {initial_deliveryman.username} 拒绝任务，原因: {rejection_reason1}'
            )
            DeliveryStatusRecord.objects.filter(id=record2.id).update(created_at=rejection_time1)
            records.append(record2)
            
            # 第二次分配给另一个配送员
            second_deliveryman = random.choice([dm for dm in all_deliverymen if dm != initial_deliveryman])
            reassign_time = rejection_time1 + timedelta(minutes=random.randint(5, 15))
            record3 = DeliveryStatusRecord.objects.create(
                delivery_task=task,
                status='assigned',
                operator=delivery_admin_user,
                note=f'系统自动分配任务给配送员: {second_deliveryman.username}，区域: 北京市{district}'
            )
            DeliveryStatusRecord.objects.filter(id=record3.id).update(created_at=reassign_time)
            records.append(record3)
            
            # 第二次拒绝
            rejection_time2 = reassign_time + timedelta(minutes=random.randint(10, 30))
            rejection_reason2 = random.choice(rejection_reasons)
            record4 = DeliveryStatusRecord.objects.create(
                delivery_task=task,
                status='rejected',
                operator=second_deliveryman,
                note=f'配送员 {second_deliveryman.username} 第二次拒绝任务，原因: {rejection_reason2}。任务已转为等待手动分配状态。'
            )
            DeliveryStatusRecord.objects.filter(id=record4.id).update(created_at=rejection_time2)
            records.append(record4)
            
            # 更新任务状态为等待手动分配
            task.status = 'awaiting_manual_assignment'
            task.deliveryman = None
            task.save()
            
            # 管理员手动分配
            manual_assign_time = rejection_time2 + timedelta(minutes=random.randint(15, 45))
            final_deliveryman = random.choice(all_deliverymen)
            task.deliveryman = final_deliveryman
            task.status = 'assigned'
            task.save()
            
            record5 = DeliveryStatusRecord.objects.create(
                delivery_task=task,
                status='assigned',
                operator=delivery_admin_user,
                note=f'任务已分配给配送员ID: {final_deliveryman.id}'
            )
            DeliveryStatusRecord.objects.filter(id=record5.id).update(created_at=manual_assign_time)
            records.append(record5)
            
            # 根据任务状态添加后续记录
            if task.status in ['delivering', 'completed']:
                delivering_time = manual_assign_time + timedelta(hours=random.randint(1,2), minutes=random.randint(0,59))
                record6 = DeliveryStatusRecord.objects.create(
                    delivery_task=task,
                    status='delivering',
                    operator=final_deliveryman,
                    note='配送员开始配送'
                )
                DeliveryStatusRecord.objects.filter(id=record6.id).update(created_at=delivering_time)
                records.append(record6)
                
                if task.status == 'completed':
                    completed_time = delivering_time + timedelta(hours=random.randint(1,5), minutes=random.randint(0,59))
                    if task.actual_delivery_time and completed_time > task.actual_delivery_time:
                        completed_time = task.actual_delivery_time
                    
                    record7 = DeliveryStatusRecord.objects.create(
                        delivery_task=task,
                        status='completed',
                        operator=final_deliveryman,
                        note='配送员已完成配送'
                    )
                    DeliveryStatusRecord.objects.filter(id=record7.id).update(created_at=completed_time)
                    records.append(record7)

    print(f'成功创建了 {awaiting_manual_count} 个等待手动分配的配送任务')
    return records

# 主函数
async def main():
    # 清除现有数据
    await sync_to_async(clear_existing_data)()
    
    # 创建用户
    users = await sync_to_async(create_users)()
    
    # 创建产品类别
    categories = await sync_to_async(create_categories)()
    
    # 创建仓库
    warehouses = await sync_to_async(create_warehouses)(users['admin'])
    
    # 创建产品
    products = await sync_to_async(create_products)(categories, users['supplier'])
    
    # 创建库存
    inventories = await sync_to_async(create_inventory)(products, warehouses)
    
    # 创建库存记录
    inventory_records = await sync_to_async(create_inventory_records)(inventories, users)
    
    # 创建采购订单
    purchase_orders = await sync_to_async(create_purchase_orders)(products, warehouses, users)
    
    # 创建配送区域
    delivery_areas = await sync_to_async(create_delivery_areas)()
    
    # 创建配送员区域关联
    deliveryman_areas = await sync_to_async(create_deliveryman_areas)(users['deliverymen'], delivery_areas)
    
    # 创建销售订单
    sales_orders = await sync_to_async(create_sales_orders)(products, warehouses, users)
    
    # 创建配送任务
    delivery_tasks = await sync_to_async(create_delivery_tasks)(sales_orders, users)
    
    # 创建配送状态记录
    delivery_status_records = await sync_to_async(create_delivery_status_records)(delivery_tasks, users)
    
    print('测试数据生成完成！')

if __name__ == '__main__':
    # 运行异步主函数
    asyncio.run(main())
